package com.lfs.handler;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.WriteContext;
import com.alibaba.excel.write.handler.CellWriteHandler;
import com.alibaba.excel.write.handler.SheetWriteHandler;
import com.alibaba.excel.write.handler.context.CellWriteHandlerContext;
import com.alibaba.excel.write.handler.context.SheetWriteHandlerContext;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.lfs.Gui;
import com.lfs.domain.DailyDataManagement;
import com.lfs.domain.MonthQuestionnaire;
import com.lfs.utils.FileUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Sheet;

import javax.swing.*;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import static com.lfs.utils.ConvertUtil.modifyData;

/**
 * excel处理操作
 */
@Slf4j
public class ExcelHandler extends Gui {
    public void processExcelFile(File excelFile) {
        try {
            // 读取Excel文件
            List<DailyDataManagement> data = EasyExcel.read(excelFile)
                    .head(DailyDataManagement.class)
                    .sheet(0)
                    .doReadSync();
            // 修改数据
            List<List<MonthQuestionnaire>> lists = modifyData(data);
//            List<List<String>> lists = convertToExcelData(monthQuestionnaires);

            // 从服务器下载模板文件
            File templateFile = new FileUtil().getTemplateFromServer("8.148.146.195", "root", System.getenv("PASSWORD"), "/lfs/files/MonthQuestionnaire.xlsx");

            for (List<MonthQuestionnaire> monthQuestionnaires : lists) {
                // 保存到新文件
                String outputFileName = "问卷调查表-"+monthQuestionnaires.get(0).getMr()+".xlsx";
                File outputFile = new File(excelFile.getParent(), outputFileName);

                // 使用EasyExcel写入数据
//            EasyExcel.write(outputFile, MonthQuestionnaire.class)
//                    .withTemplate(templateFile)
//                    .sheet("待复制")
//                    .registerWriteHandler(new SheetWriteFormatHandler())
////                    .registerWriteHandler(new DropdownWriteHandler(data.stream().map(DailyDataManagement::getHospital).distinct().collect(Collectors.toList())))
//                    .doWrite(monthQuestionnaires);
                // 使用poi写入数据
                PoiHandler.export(templateFile.getAbsolutePath(), outputFile.getAbsolutePath(), monthQuestionnaires);
                JOptionPane.showMessageDialog(frame, "处理完成！文件已保存为："+outputFile.getAbsolutePath());
            }
            // 删除模板文件
            if (!templateFile.delete()) {
                log.warn("无法删除模板文件: {}", templateFile.getAbsolutePath());
            }
        } catch (Exception ex) {
            log.error("处理Excel文件时出错:",ex);
            JOptionPane.showMessageDialog(frame, ex.getMessage());
        }
    }
}
